from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
import os

from src.database.models import Base
from src.config import SQLALCHEMY_DATABASE_URI

class DBManager:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(DBManager, cls).__new__(cls)
            cls._instance.engine = create_engine(SQLALCHEMY_DATABASE_URI)
            cls._instance.SessionLocal = sessionmaker(
                autocommit=False, 
                autoflush=False, 
                bind=cls._instance.engine
            )
        return cls._instance
    
    def get_session(self):
        return self.SessionLocal()
    
    def init_db(self):
        inspector = inspect(self.engine)
        
        # Get all table names defined in Base.metadata
        model_tables = Base.metadata.tables.keys()
        
        # Get all existing tables in the database
        existing_tables = inspector.get_table_names()
        
        # Find tables that don't exist
        missing_tables = [table for table in model_tables if table not in existing_tables]
        
        if missing_tables:
            # Create all tables
            Base.metadata.create_all(self.engine)
            print(f"Created tables: {', '.join(missing_tables)}")
        else:
            print("All database tables already exist.")